package com.moss.cloud.auth.biz.utils;

import com.moss.cloud.common.base.model.po.SysUser;
import com.moss.cloud.common.core.model.dto.UserLoginDTO;
import com.moss.cloud.common.core.utils.BooleanHandel;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import com.moss.cloud.common.core.utils.IpUtil;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

public class UserAgentUtil {
    /**
     * 失败方法
     *
     * @param request
     * @param login
     * @param event
     * @return UserLogin
     * @date 2020/04/30
     * @author 瑾年
     */
    public static final UserLoginDTO getFail(HttpServletRequest request,
                                             String login,
                                             AuthenticationFailureBadCredentialsEvent event,
                                             SysUser sysUser) {
        BooleanHandel.isTrue(Objects.nonNull(sysUser) && Objects.isNull(sysUser.getTenantId())).trueHandle(()-> sysUser.setTenantId(0L));
        BooleanHandel.isTrue(Objects.isNull(sysUser)).trueHandle(()-> sysUser.setTenantId(0L));
        UserLoginDTO dto = getPublic(request, login, sysUser);
        dto.setAccountNumber(event.getAuthentication().getName());
        return dto;
    }

    /**
     * 成功方法
     *
     * @param request
     * @param login
     * @param event
     * @return UserLogin
     * @date 2020/04/30
     * @author 瑾年
     */
    public static final UserLoginDTO getSuccess(HttpServletRequest request,
                                                String login, AuthenticationSuccessEvent event, SysUser sysUser) {
        UserLoginDTO dto = getPublic(request, login, sysUser);
        dto.setAccountNumber(event.getAuthentication().getName());
        return dto;
    }

    /**
     * 公用方法
     *
     * @param request
     * @param login
     * @return UserLogin
     * @date 2020/04/30
     * @author 瑾年
     */
    private static UserLoginDTO getPublic(HttpServletRequest request, String login, SysUser sysUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        UserLoginDTO dto = new UserLoginDTO();
        dto.setLoginStatus(login);
        dto.setEquipment(userAgent.getOperatingSystem().getDeviceType()
                + "-" + userAgent.getOperatingSystem().getName());
        dto.setRemoteIp(IpUtil.getIpAddr(request));
        dto.setLoginTime(LocalDateTime.now());
        dto.setTenantId(Objects.nonNull(sysUser.getTenantId()) ? sysUser.getTenantId() : 0L);
        return dto;
    }
}
